﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

//using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Autodesk.AutoCAD;

//using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using Microsoft.VisualBasic;
using MyCadDll.MyObject;
using MyTool.FileOpt;

namespace MyCadDll
{
    public class MyCad
    {
        private Autodesk.AutoCAD.Interop.AcadApplication AcadApp;
        private Autodesk.AutoCAD.Interop.AcadDocument AcadDoc;
        private AcadSelectionSet mySelectionSet = null;
        public List<MyLine> m_listMyLine = new List<MyLine>();
        public List<MyText> m_listMyText = new List<MyText>();
        private Dictionary<string, MyBlock> myBlockDic = new Dictionary<string, MyBlock>();
        private IniFile myini;

        // ThreadPool threadpool;
        private Mutex mutex_addText;

        private Mutex mutex_addLine;
        private int intset;

        public MyCad()
        {
            mutex_addText = new Mutex();
            mutex_addLine = new Mutex();
            myini = new IniFile("./\\mycad.ini");
            myini.Load();
        }

        public MyCad(string iniFileName)
        {
            myini = new IniFile(iniFileName);
            myini.Load();
        }

        //启动CAD文件
        public void StartCad()
        {
            try
            {
                AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                AcadDoc = AcadApp.ActiveDocument;
            }
            catch
            {
                OpenFileDialog POpenDG = new OpenFileDialog();
                POpenDG.ShowDialog();
                string filePath = POpenDG.FileName;
                AcadApp = new AcadApplication();
                AcadDoc = AcadApp.Documents.Open(filePath, null, null);
            }
            AcadApp.Application.Visible = true;
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        }

        #region CAD选择集到数组相关操作

        //public string[] GetSelectSet(string style)
        //{
        //    intset++;
        //    string NewSelectionSet003 = intset.ToString();
        //    Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        //    mySelectionSet = AcadDoc.SelectionSets.Add(NewSelectionSet003);
        //    Int16[] FilterType = new Int16[1];
        //    object[] FilterData = new object[1];
        //    FilterType[0] = 0;
        //    FilterData[0] = "*";
        //    mySelectionSet.SelectOnScreen(FilterType, FilterData);
        //    int z = mySelectionSet.Count;
        //    String[] textArray = new String[z];
        //    int count = 0;

        //    object p1 = new double[3];
        //    object p2 = new double[3];
        //    foreach (AcadObject acadObj in mySelectionSet)
        //    {
        //        if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
        //        {
        //            textArray[count++] = ((AcadText)acadObj).TextString;
        //            ((AcadText)acadObj).GetBoundingBox(out p1, out p2);
        //            System.Diagnostics.Trace.TraceInformation(((double[])p1)[1] + " " + ((double[])p1)[0]);
        //        }
        //    }
        //    AcadDoc.SelectionSets.Item(NewSelectionSet003).Delete();
        //    //AcadDoc.SelectionSets.Item(NewSelectionSet003) = null;
        //    Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        //    return textArray;
        //}

        public void GetSelectSet()
        {
            CreateSelectSet();
            if (mySelectionSet == null)
            {
                return;
            }
            Int16[] FilterType = new Int16[1];
            object[] FilterData = new object[1];
            FilterType[0] = 0;
            FilterData[0] = "*";
            mySelectionSet.SelectOnScreen(FilterType, FilterData);
            //Stopwatch st = new Stopwatch();
            //st.Start();

            #region 单线程处理

            //foreach (AcadObject acadObj in mySelectionSet)
            //{
            //    DealData(acadObj);
            //}

            #endregion 单线程处理

            #region 多线程处理

            int preThreadDealCount = 500;
            int n1 = mySelectionSet.Count / preThreadDealCount + 1;
            int threadCount = n1 < 20 ? n1 : 20;
            ThreadPool.SetMaxThreads(threadCount, threadCount);
            ManualResetEvent[] _ManualEvents = new ManualResetEvent[threadCount];
            int count = mySelectionSet.Count / threadCount;
            int z = 0;
            for (int i = 0; i < mySelectionSet.Count; i = i + preThreadDealCount)
            {
                int n2 = i + preThreadDealCount - 1;
                if (n2 >= mySelectionSet.Count) n2 = mySelectionSet.Count - 1;
                ThreadPoolObject poolObj = new ThreadPoolObject(i, n2);
                _ManualEvents[z] = poolObj.ManuaE;
                if (++z >= threadCount) z = 0;
                ThreadPool.QueueUserWorkItem(new WaitCallback(DealData), poolObj);
            }
            ThreadPool.SetMaxThreads(threadCount, threadCount);
            for (int i = 0; i < _ManualEvents.Length; i++)
            {
                if (_ManualEvents[i] != null)
                    _ManualEvents[i].WaitOne();
            }

            #endregion 多线程处理

            //st.Stop();
            //Trace.TraceInformation(st.ElapsedMilliseconds.ToString());
            ReleaseSelectionSet();
        }

        private void GetBlockRefData(AcadObject acadObj, double[] insertPointOffset)
        {
            if (acadObj.ObjectName == "AcDbBlockReference")
            {
                AcadBlockReference blockRef = acadObj as AcadBlockReference;
                double[] p1 = (double[])blockRef.InsertionPoint;
                for (int i = 0; i < 3; i++)
                {
                    p1[i] += insertPointOffset[i];
                }
                string refEffectName = blockRef.EffectiveName;
                //如果是快引用，把该快取出来，存入字典
                //if (myBlockDic.ContainsKey(refEffectName) == false)
                //{
                AcadDocument doc = (AcadDocument)blockRef.Document;
                AcadDatabase database = (AcadDatabase)doc.Database;
                AcadBlocks blocks = (AcadBlocks)database.Blocks;

                foreach (AcadBlock block in blocks)
                {
                    string blockName = block.Name;
                    if (blockName != refEffectName)
                        continue;
                    GetBlockData(block, p1);
                    break;
                }
                //}
                if (myBlockDic.ContainsKey(refEffectName))
                {
                    MyBlock block1 = myBlockDic[refEffectName];
                    foreach (MyLine line in block1.myLineList)
                    {
                        MyLine newLine = new MyLine();
                        newLine.P1 = line.P1 + p1;
                        newLine.P2 = line.P2 + p1;
                        //m_listMyLine.Add(newLine);
                        AddLine(newLine);
                    }
                    foreach (MyText text in block1.myTextList)
                    {
                        MyText newText = new MyText(text.Text, text.Point + p1);
                        // m_listMyText.Add(newText);
                        AddText(newText);
                    }
                }
                if (blockRef.HasAttributes)
                {
                    AcadAttributeReference attr;
                    object[] ob = (object[])blockRef.GetAttributes();
                    for (int i = 0; i < ob.Length; i++)
                    {
                        attr = ob[i] as AcadAttributeReference;
                        double[] p2 = (double[])attr.InsertionPoint;
                        string str1 = attr.TextString;
                        MyText text = new MyText(str1, new MyPoint(p2));
                        // m_listMyText.Add(text);
                        AddText(text);
                    }
                }
            }
        }

        /// <summary>
        /// 如果字典中没有该块的信息，则把该快的信息存入字典
        /// </summary>
        /// <param name="block"></param>
        private void GetBlockData(AcadBlock block, double[] insertPointOffset)
        {
            MyBlock myBlock = new MyBlock();
            int n = block.Count;
            AcInsertUnits units = block.Units;

            for (int i = 0; i < n; i++)
            {
                AcadEntity entity = block.Item(i);
                AcadObject obj = entity as AcadObject;
                GetBlockRefData(obj, insertPointOffset);
                SetMyLines(obj, myBlock.myLineList);
                SetMyTexts(obj, myBlock.myTextList);
            }
            if (myBlockDic.ContainsKey(block.Name) == false)
            {
                myBlockDic.Add(block.Name, myBlock);
            }
            else
            {
                myBlockDic[block.Name] = myBlock;
            }
        }

        /// <summary>
        /// 如果acadObj为直线类型，把他存入直线列表
        /// </summary>
        /// <param name="acadObj"></param>
        private void SetMyLines(AcadObject acadObj)
        {
            if (acadObj.ObjectName == "AcDbPolyline")
            {
                double[] d1;
                AcadLWPolyline lwLine = (AcadLWPolyline)acadObj;
                d1 = (double[])lwLine.Coordinates;

                int l = d1.Length;
                for (int i = 0; i + 3 < l; i += 2)
                {
                    MyPoint myPoint1 = new MyPoint(d1[i], d1[i + 1]);
                    MyPoint myPoint2 = new MyPoint(d1[i + 2], d1[i + 3]);
                    MyLine myLine = new MyLine(myPoint1, myPoint2);
                    // m_listMyLine.Add(myLine);
                    AddLine(myLine);
                }
                if (lwLine.Closed == true)
                {
                    MyPoint myPoint1 = new MyPoint(d1[0], d1[1]);
                    MyPoint myPoint2 = new MyPoint(d1[l - 2], d1[l - 1]);
                    MyLine myLine = new MyLine(myPoint1, myPoint2);
                    //m_listMyLine.Add(myLine);
                    AddLine(myLine);
                }
            }
            if (acadObj.ObjectName == "AcDbLine")
            {
                AcadLine line = (AcadLine)acadObj;
                MyPoint myPoint1 = new MyPoint((double[])line.StartPoint);
                MyPoint myPoint2 = new MyPoint((double[])line.EndPoint);
                MyLine myLine = new MyLine(myPoint1, myPoint2);
                //m_listMyLine.Add(myLine);
                AddLine(myLine);
            }
        }

        private void SetMyLines(AcadObject acadObj, List<MyLine> list)
        {
            if (acadObj.ObjectName == "AcDbPolyline")
            {
                double[] d1;
                AcadLWPolyline lwLine = (AcadLWPolyline)acadObj;
                d1 = (double[])lwLine.Coordinates;

                int l = d1.Length;
                for (int i = 0; i + 3 < l; i += 2)
                {
                    MyPoint myPoint1 = new MyPoint(d1[i], d1[i + 1]);
                    MyPoint myPoint2 = new MyPoint(d1[i + 2], d1[i + 3]);
                    MyLine myLine = new MyLine(myPoint1, myPoint2);
                    list.Add(myLine);
                }
                if (lwLine.Closed == true)
                {
                    MyPoint myPoint1 = new MyPoint(d1[0], d1[1]);
                    MyPoint myPoint2 = new MyPoint(d1[l - 2], d1[l - 1]);
                    MyLine myLine = new MyLine(myPoint1, myPoint2);
                    list.Add(myLine);
                }
            }
            if (acadObj.ObjectName == "AcDbLine")
            {
                AcadLine line = (AcadLine)acadObj;
                MyPoint myPoint1 = new MyPoint((double[])line.StartPoint);
                MyPoint myPoint2 = new MyPoint((double[])line.EndPoint);
                MyLine myLine = new MyLine(myPoint1, myPoint2);
                list.Add(myLine);
            }
        }

        /// <summary>
        /// 如果acadObj为文字，把它存入到文字列表中
        /// </summary>
        /// <param name="acadObj"></param>
        private void SetMyTexts(AcadObject acadObj)
        {
            if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
            {
                string str = acadObj.ObjectName == "AcDbText" ? ((AcadText)acadObj).TextString : ((AcadMText)acadObj).TextString;
                object p1 = new double[3];
                double[] d = acadObj.ObjectName == "AcDbText" ? (double[])((AcadText)acadObj).InsertionPoint : (double[])((AcadMText)acadObj).InsertionPoint; ;
                MyPoint myPoint1 = new MyPoint(d[0], d[1]);
                MyText myText = new MyText(str, myPoint1);
                //m_listMyText.Add(myText);
                AddText(myText);
            }
        }

        private void SetMyTexts(AcadObject acadObj, List<MyText> list)
        {
            if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
            {
                string str = acadObj.ObjectName == "AcDbText" ? ((AcadText)acadObj).TextString : ((AcadMText)acadObj).TextString;
                object p1 = new double[3];
                object p2 = new double[3];
                double[] d = (double[])((AcadText)acadObj).InsertionPoint;
                MyPoint myPoint1 = new MyPoint(d[0], d[1]);
                MyText myText = new MyText(str, myPoint1);
                list.Add(myText);
            }
        }

        #endregion CAD选择集到数组相关操作

        //读选择集到mycad.ini的‘cad数据’节中
        public void ReadSelectSetToIni()
        {
            intset++;
            string NewSelectionSet003 = intset.ToString();
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            mySelectionSet = AcadDoc.SelectionSets.Add(NewSelectionSet003);
            Int16[] FilterType = new Int16[1];
            object[] FilterData = new object[1];
            FilterType[0] = 0;
            FilterData[0] = "*";
            mySelectionSet.SelectOnScreen(FilterType, FilterData);
            int tempsum = myini.GetInt("CAD数据", "sum", 0);
            foreach (AcadObject acadObj in mySelectionSet)
            {
                if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
                {
                    myini.WriteString("CAD数据", (++tempsum).ToString(), ((AcadText)acadObj).TextString);
                }
                myini.WriteInt("CAD数据", "sum", tempsum);
            }
            myini.Save();
            AcadDoc.SelectionSets.Item(NewSelectionSet003).Delete();
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        }

        private AcadSelectionSet CreateSelectSet()
        {
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            string NewSelectionSet003;
            while (true)
            {
                NewSelectionSet003 = intset.ToString();
                try
                {
                    mySelectionSet = AcadDoc.SelectionSets.Add(NewSelectionSet003);
                    break;
                }
                catch
                {
                    intset++;
                    continue;
                }
            }
            return mySelectionSet;
        }

        private void ReleaseSelectionSet()
        {
            AcadDoc.SelectionSets.Item(intset.ToString()).Delete();
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        }

        /// <summary>
        /// 文字替换
        /// </summary>
        /// <param name="sourText"></param>
        /// <param name="destText"></param>
        public void ReplaceText(string sourText, string destText)
        {
            mySelectionSet = CreateSelectSet();
            Int16[] FilterType = new Int16[1];
            object[] FilterData = new object[1];
            FilterType[0] = 0;
            FilterData[0] = "*";
            mySelectionSet.SelectOnScreen(FilterType, FilterData);
            foreach (AcadObject acadObj in mySelectionSet)
            {
                if (acadObj is AcadLine)
                //if (acadObj.ObjectName == "AcDbLine")
                {
                    AcadLine line = acadObj as AcadLine;
                    object o = line.StartPoint;
                }
                Type t = acadObj.GetType();
                Type[] interfaces = t.GetInterfaces();
                Type t1 = t.BaseType;
                string str = t.Name;
                if (acadObj is AcadLWPolyline)
                //if (acadObj.ObjectName == "AcDbPolyline")
                {
                    AcadLWPolyline polyLine = acadObj as AcadLWPolyline;
                    object obj = polyLine.Coordinates;
                }
                if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
                {
                    #region 如果是AcDbText类型

                    if (acadObj.ObjectName == "AcDbText")
                    {
                        AcadText atext = acadObj as AcadText;
                        if (atext.TextString.Contains(sourText))
                        {
                            atext.TextString = atext.TextString.Replace(sourText, destText);
                        }
                    }

                    #endregion 如果是AcDbText类型

                    #region 如果是AcDbMText类型

                    if (acadObj.ObjectName == "AcDbMText")
                    {
                        AcadMText atext = acadObj as AcadMText;
                        if (atext.TextString.Contains(sourText))
                        {
                            atext.TextString = atext.TextString.Replace(sourText, destText);
                        }
                    }

                    #endregion 如果是AcDbMText类型
                }
            }
            ReleaseSelectionSet();
            //AcadDoc.SelectionSets.Item(NewSelectionSet003).Delete();
            //Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
        }

        //读选择集到mycad.ini的指定section节中
        public void ReadSelectSetToIni(string section)
        {
            //intset++;
            //string NewSelectionSet003 = intset.ToString();
            //Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            //mySelectionSet = AcadDoc.SelectionSets.Add(NewSelectionSet003);
            mySelectionSet = CreateSelectSet();
            Int16[] FilterType = new Int16[1];
            object[] FilterData = new object[1];
            FilterType[0] = 0;
            FilterData[0] = "*";
            mySelectionSet.SelectOnScreen(FilterType, FilterData);
            int tempsum = myini.GetInt(section, "sum", 0);
            foreach (AcadObject acadObj in mySelectionSet)
            {
                if (acadObj.ObjectName == "AcDbText" || acadObj.ObjectName == "AcDbMText")
                {
                    myini.WriteString(section, (++tempsum).ToString(), ((AcadText)acadObj).TextString);
                }
                myini.WriteInt(section, "sum", tempsum);
            }
            ReleaseSelectionSet();
        }

        #region Draw操作

        public void WriteToCad(double[] p, String s, int height)
        {
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadDoc.ModelSpace.AddText(s, p, height);
        }

        //public void WriteIniToJyCad()
        //{
        //    int x = 25;
        //    int[] y = { 0, 10, 12, 15, 12, 12, 13, 13, 11, 14, 14, 11, 12, 13, 11, 14 };
        //    double[] p1 = { 200, 800, 0 };
        //    double[] p2 = { 200, 800, 0 };
        //    string name1, pei;
        //    int sum = myini.GetInt("jy", "sum", 0);
        //    int j = 1;
        //    List<string> listName = new List<string>();
        //    List<string> listPei = new List<string>();
        //    for (int i = 1; i <= sum; i++)
        //    {
        //        string[] strs = myini.GetString("dy", i.ToString()).Split(new char[] { ' ', ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
        //        name1 = name1 = strs.Length > 0 ? strs[0] : "error"; //myini.GetString("jy", i.ToString(), "error2", 0);
        //        if (name1 == "error2") continue;
        //        pei = name1 = strs.Length > 1 ? strs[1] : "error";//myini.GetString("jy", i.ToString(), "", 1);
        //        if (name1.EndsWith("X3") || name1.EndsWith("X4") || name1.EndsWith("X5"))
        //        {
        //            listName.Add(name1);
        //            listPei.Add(pei);
        //            continue;
        //        }
        //        p1[1] = p1[1] - y[(j - 1) % 16];
        //        WriteToCad(p1, name1, 2);
        //        p1[0] = p1[0] + x;
        //        WriteToCad(p1, pei, 2);
        //        p1[0] = p2[0];
        //        if (j % 16 == 0)
        //        {
        //            p2[0] = p2[0] + 2 * x;
        //            p1[0] = p2[0];
        //            p1[1] = p2[1];
        //        }
        //        j++;
        //    }
        //    p2[0] = p2[0] + 2 * x;
        //    p1[0] = p2[0];
        //    p1[1] = p2[1];
        //    j = 1;
        //    for (int k = 0; k < listName.Count; k++)
        //    {
        //        p1[1] = p1[1] - y[(j - 1) % 8];
        //        WriteToCad(p1, listName[k], 2);
        //        p1[0] = p1[0] + x;
        //        WriteToCad(p1, listPei[k], 2);
        //        p1[0] = p2[0];
        //        if (j % 8 == 0)
        //        {
        //            p2[0] = p2[0] + 2 * x;
        //            p1[0] = p2[0];
        //            p1[1] = p2[1];
        //        }
        //        j++;
        //    }
        //}

        //public void WriteIniToDyCad()
        //{
        //    int x = 25;
        //    //int[] y = { 0, 10, 12, 15, 12, 12, 13, 13, 11, 14, 14, 11, 12, 13, 11, 14 };
        //    int[] y = { 0, 22, 27, 25, 24, 28, 23, 24 };
        //    double[] p1 = { 200, 600, 0 };
        //    double[] p2 = { 200, 600, 0 };
        //    string name1;
        //    int sum = myini.GetInt("dy", "sum", 0);
        //    for (int i = 1; i <= sum; i++)
        //    {
        //        string[] strs = myini.GetString("dy", i.ToString()).Split(new char[] { ' ', ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
        //        p1[1] = p1[1] - y[(i - 1) % 8];
        //        name1 = strs.Length > 0 ? strs[0] : "error";//myini.GetString("dy", i.ToString(), "error2", 0);
        //        WriteToCad(p1, name1, 2);
        //        name1 = strs.Length > 1 ? strs[1] : "error"; // myini.GetString("dy", i.ToString(), "", 1);
        //        p1[0] = p1[0] + x;
        //        WriteToCad(p1, name1, 2);
        //        p1[0] = p2[0];
        //        if (i % 8 == 0)
        //        {
        //            p2[0] = p2[0] + 2 * x;
        //            p1[0] = p2[0];
        //            p1[1] = p2[1];
        //        }
        //    }
        //}

        public void WriteIniToJyCad()
        {
            int x = 25;
            int[] y = { 0, 10, 12, 15, 12, 12, 13, 13, 11, 14, 14, 11, 12, 13, 11, 14 };
            double[] p1 = { 200, 800, 0 };
            double[] p2 = { 200, 800, 0 };
            string name1, pei;
            int sum = myini.GetInt("jy", "sum", 0);
            int j = 1;
            List<string> listName = new List<string>();
            List<string> listPei = new List<string>();
            for (int i = 1; i <= sum; i++)
            {
                name1 = myini.GetString("jy", i.ToString());
                if (string.IsNullOrEmpty(name1)) continue;
                string[] strs = name1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                name1 = strs.Length > 0 ? strs[0] : "";
                if (name1 == "") continue;
                pei = strs.Length > 1 ? strs[1] : "";
                if (name1.EndsWith("X3") || name1.EndsWith("X4") || name1.EndsWith("X5"))
                {
                    listName.Add(name1);
                    listPei.Add(pei);
                    continue;
                }
                p1[1] = p1[1] - y[(j - 1) % 16];
                WriteToCad(p1, name1, 2);
                p1[0] = p1[0] + x;
                WriteToCad(p1, pei, 2);
                p1[0] = p2[0];
                if (j % 16 == 0)
                {
                    p2[0] = p2[0] + 2 * x;
                    p1[0] = p2[0];
                    p1[1] = p2[1];
                }
                j++;
            }
            p2[0] = p2[0] + 2 * x;
            p1[0] = p2[0];
            p1[1] = p2[1];
            j = 1;
            for (int k = 0; k < listName.Count; k++)
            {
                p1[1] = p1[1] - y[(j - 1) % 8];
                WriteToCad(p1, listName[k], 2);
                p1[0] = p1[0] + x;
                WriteToCad(p1, listPei[k], 2);
                p1[0] = p2[0];
                if (j % 8 == 0)
                {
                    p2[0] = p2[0] + 2 * x;
                    p1[0] = p2[0];
                    p1[1] = p2[1];
                }
                j++;
            }
        }

        public void WriteIniToDyCad()
        {
            int x = 25;
            //int[] y = { 0, 10, 12, 15, 12, 12, 13, 13, 11, 14, 14, 11, 12, 13, 11, 14 };
            int[] y = { 0, 22, 27, 25, 24, 28, 23, 24 };
            double[] p1 = { 200, 600, 0 };
            double[] p2 = { 200, 600, 0 };
            string name1;
            int sum = myini.GetInt("dy", "sum", 0);
            for (int i = 1; i <= sum; i++)
            {
                p1[1] = p1[1] - y[(i - 1) % 8];
                name1 = myini.GetString("dy", i.ToString());
                if (string.IsNullOrEmpty(name1)) continue;
                string[] strs = name1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string name2 = strs.Length > 0 ? strs[0] : "";
                if (name2 == "") continue;

                WriteToCad(p1, name2, 2);
                name2 = strs.Length > 1 ? strs[1] : "";

                p1[0] = p1[0] + x;
                WriteToCad(p1, name2, 2);
                p1[0] = p2[0];
                if (i % 8 == 0)
                {
                    p2[0] = p2[0] + 2 * x;
                    p1[0] = p2[0];
                    p1[1] = p2[1];
                }
            }
        }

        public void DrawTextToCad(double[] p, String s, double height)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadText t = AcadDoc.ModelSpace.AddText(s, p, height);
        }

        public void DrawTextToCad(double[] p, String s, double height, double rotation)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadText t = AcadDoc.ModelSpace.AddText(s, p, height);
            t.Rotation = rotation;
        }

        public void DrawLineToCad(double[] p1, double[] p2, int weight)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadLine line = AcadDoc.ModelSpace.AddLine(p1, p2);
            // line.Lineweight = (ACAD_LWEIGHT)weight;
        }

        public void DrawLineToCad(double[] p, int weight)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadLine line = AcadDoc.ModelSpace.AddLine(new double[] { p[0], p[1], p[2] }, new double[] { p[3], p[4], p[5] });
            line.Lineweight = (ACAD_LWEIGHT)weight;
        }

        public void DrawRectToCad(object list, double width)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadPolyline pl = AcadDoc.ModelSpace.AddPolyline(list);
            pl.ConstantWidth = width;
        }

        public void DrawLinesToCad(double[][] points1, double[][] points2, int count)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            for (int i = 0; i < count; i++)
            {
                AcadDoc.ModelSpace.AddLine(points1[i], points2[i]);
            }
        }

        public void DrawCircleToCad(object center, double radius)
        {
            if (AcadApp == null)
            {
                try
                {
                    AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                    AcadDoc = AcadApp.ActiveDocument;
                }
                catch
                {
                    OpenFileDialog POpenDG = new OpenFileDialog();
                    POpenDG.ShowDialog();
                    string filePath = POpenDG.FileName;
                    AcadApp = new AcadApplication();
                    AcadDoc = AcadApp.Documents.Open(filePath, null, null);
                }
            }
            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadCircle circle = AcadDoc.ModelSpace.AddCircle(center, radius);
        }

        #endregion Draw操作

        private void AddText(MyText text)
        {
            //mutex_addText.WaitOne();
            m_listMyText.Add(text);
            //mutex_addText.ReleaseMutex();
        }

        private void AddLine(MyLine line)
        {
            //mutex_addLine.WaitOne();
            m_listMyLine.Add(line);
            //mutex_addLine.ReleaseMutex();
        }

        private void DealData(int start, int end)
        {
            for (int i = start; i < end; i++)
            {
                DealData(mySelectionSet.Item(i) as object);
            }
        }

        private void DealData(object obj)
        {
            double[] insertPointOffset = new double[] { 0, 0, 0 };
            if (obj is ThreadPoolObject)
            {
                ThreadPoolObject poolObject = obj as ThreadPoolObject;
                for (int i = poolObject.Start; i <= poolObject.End; i++)
                {
                    AcadObject acadObj = mySelectionSet.Item(i) as AcadObject;
                    GetBlockRefData(acadObj, insertPointOffset);
                    SetMyLines(acadObj);
                    SetMyTexts(acadObj);
                }
                poolObject.ManuaE.Set();
            }
            else if (obj is AcadObject)
            {
                AcadObject obj1 = obj as AcadObject;
                GetBlockRefData(obj1, insertPointOffset);
                SetMyLines(obj1);
                SetMyTexts(obj1);
            }
        }
    }
}